﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace SchoolManagement.Utilities
{
    public static class Utilities
    {
        public static List<T> FindControl<T>(System.Web.UI.Page page) where T : Control
        {
            List<T> list = new List<T>();
            return FindControl<T>(page, list);
        }
        public static List<T> FindControl<T>(Control startingControl, List<T> list) where T : Control
        {
            // this is null by default
            T found = default(T);

            int controlCount = startingControl.Controls.Count;

            if (controlCount > 0)
            {
                for (int i = 0; i < controlCount; i++)
                {
                    Control activeControl = startingControl.Controls[i];
                    if (activeControl is T)
                    {
                        found = startingControl.Controls[i] as T;
                        list.Add(found);
                        //break;
                        //if(found.GetType() == myType) break;
                        // else found = null;
                    }
                    else
                    {
                        list = FindControl<T>(activeControl, list);
                        //if (found != null) break;
                    }
                }
            }
            return list;
        }

        public static T FindControl<T>(string id, System.Web.UI.Page page) where T : Control
        {
            return FindControl<T>(page, id);
        }

        public static T FindControl<T>(Control startingControl, string id) where T : Control
        {
            // this is null by default
            T found = default(T);

            int controlCount = startingControl.Controls.Count;

            if (controlCount > 0)
            {
                for (int i = 0; i < controlCount; i++)
                {
                    Control activeControl = startingControl.Controls[i];
                    if (activeControl is T)
                    {
                        found = startingControl.Controls[i] as T;
                        if (string.Compare(id, found.ID, true) == 0) break;
                        else found = null;
                    }
                    else
                    {
                        found = FindControl<T>(activeControl, id);
                        if (found != null) break;
                    }
                }
            }
            return found;
        }


    }
}
